--The MIT License (MIT)
--
--Copyright (c) 2016 Jaap Braam
--
--Permission is hereby granted, free of charge, to any person obtaining a copy
--of this software and associated documentation files (the "Software"), to deal
--in the Software without restriction, including without limitation the rights
--to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
--copies of the Software, and to permit persons to whom the Software is
--furnished to do so, subject to the following conditions:
--
--The above copyright notice and this permission notice shall be included in all
--copies or substantial portions of the Software.
--
--THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
--IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
--FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
--AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
--LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
--OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
--SOFTWARE.
--
--Author: Jaap Braam
station_cfg={}
function wifi_connect(config)
  -- WIFI config
    if(config.ssid ~= nil and config.pwd ~= nil) then
        print(string.format("get wifi config:\nssid:\"%s\"\npassword:\"%s\"", config.ssid, config.pwd))
        print("WIFI connecting...")
        station_cfg.ssid=config.ssid
        station_cfg.pwd=config.pwd
        station_cfg.save=true
        station_cfg.auto=true
        wifi.sta.config(station_cfg)
    end
end

function http_server(conn)
    conn:on("receive", function(client,request)
        local buf = ""
        print(request)
        local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP")
        if(method == nil)then
            _, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP")
        end
        local _GET = {}
        print(vars)
        if (vars ~= nil)then
            for k, v in string.gmatch(vars, "(%w+)=([%w_]+)&*") do
                _GET[k] = v
                print("k="..k.."v="..v)
            end
        end
        buf = buf..'HTTP/1.1 200 \r\n'
        buf = buf..'Content-Type: text/html\r\n'
        buf = buf..'\r\n'
        buf = buf.."<h1>LoRa gateway config</h1><form action=\"\">Username:<br><input type=\"text\" name=\"ssid\"><br>Passward:<br><input type=\"text\" name=\"pwd\"><br><br><input type=\"submit\" value=\"Submit\"></form>"
        if(_GET.ssid ~= nil and _GET.pwd ~= nil)then
            print(string.format("get wifi config:\nssid:\"%s\"\npassword:\"%s\"", _GET.ssid, _GET.pwd))
            wifi_connect(_GET)
        end
        client:send(buf)
    end)
    conn:on("sent", function (c) c:close() end)
end

function create_server()
    if srv ~= nil then
        return
    end
    print("creat server")
    wifi.setmode(wifi.STATIONAP)
    wifi.ap.config({ssid=ap_ssid, pwd="123456789"})
    srv=net.createServer(net.TCP)
    srv:listen(80,http_server)
end

function close_server()
    if(srv ~= nil) then
        print("close server")
        srv:close()
        wifi.setmode(wifi.STATION)
        srv = nil
    end
end
    require("Config")
    gpio.mode(CONFIG["GW_NET_STAT_IO"],gpio.OUTPUT)
    gpio.write(CONFIG["GW_NET_STAT_IO"],gpio.HIGH)

if file.exists("SX1276.lua") then
    node.compile("SX1276.lua")
    file.remove("SX1276.lua")
    node.restart()
elseif file.exists("LoRaWanGW.lua") then
    node.compile("LoRaWanGW.lua")
    file.remove("LoRaWanGW.lua")
    node.restart()
elseif file.exists("Config.lua") then
    node.compile("Config.lua")
    file.remove("Config.lua")
    node.restart()
else
   if not _G.cjson then
      _G.cjson=sjson -- use cjson to be backwards compatible with master branch
   end


    -- Press the button to reset the gateway, and the status light flashes with it
    local trig =gpio.trig
    gpio.mode(CONFIG["GW_DEV_RESET_IO"],gpio.INT)
    gpio.mode(CONFIG["GW_DEV_STAT_IO"], gpio.OUTPUT)
    local function pincb(level)
        print( "gpio down" )
        wifi.sta.disconnect()
        print( "disconnect" )
        gpio.write(CONFIG["GW_DEV_STAT_IO"],gpio.LOW)
        tmr.delay(CONFIG["GW_1_s"])
        gpio.write(CONFIG["GW_DEV_STAT_IO"],gpio.HIGH)
        tmr.delay(CONFIG["GW_1_s"])
        gpio.write(CONFIG["GW_DEV_STAT_IO"],gpio.LOW)
        tmr.delay(CONFIG["GW_1_s"])
        gpio.write(CONFIG["GW_DEV_STAT_IO"],gpio.HIGH)
        tmr.delay(CONFIG["GW_1_s"])
        wifi.sta.clearconfig()
        print( "clear" )
        node.restore()
        node.restart()
    end
    trig(CONFIG["GW_DEV_RESET_IO"], "down", pincb)

    require("LoRaWanGW")
    wifi.setmode(wifi.STATIONAP)
    ap_ssid = string.gsub(wifi.sta.getmac(),":","")
    ap_ssid="lr_"..ap_ssid;
    print("Gateway ID",ap_ssid)
    wifi.ap.config({ssid=ap_ssid, pwd="123456789"})
    local config=wifi.sta.getdefaultconfig(true)
    wifi_connect(config)
    create_server()
end
